package com.quanyan.user.service.impl;


import com.quanyan.common.constants.Constants;
import com.quanyan.user.cache.MyRedisTemplate;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.mapper.TbUserExtMapper;
import com.quanyan.user.mapper.TbUserMapper;
import com.quanyan.user.mapper.UserExtMapper;
import com.quanyan.user.mapper.UserInfoMapper;
import com.quanyan.user.model.db.TbUser;
import com.quanyan.user.model.db.TbUserExt;
import com.quanyan.user.model.db.TbUserExtExample;
import com.quanyan.user.service.UserExtService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/7/30.
 */
@Service
public class UserExtServiceImpl extends UserBaseServiceImpl implements UserExtService {

    public static final Logger logger = LoggerFactory.getLogger(UserExtServiceImpl.class);

    @Autowired
    private TbUserExtMapper tbUserExtMapper;

    @Autowired
    private MyRedisTemplate myRedisTemplate;

    @Autowired
    private TbUserMapper userMapper;

    @Autowired
    private UserExtMapper userExtMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public TbUserExt getTbUserExt(Integer uid) {
        String extKey = UserConstants.getUserExtRedisKey(uid);
        TbUserExt tbUserExt = (TbUserExt)myRedisTemplate.get(extKey);
        if(tbUserExt == null){
            tbUserExt = this.getExt(uid);
        }
        if (StringUtils.isBlank(tbUserExt.getBgUrl())) {
            TbUserExt userExt = new TbUserExt();
            userExt.setUid(uid);
            //随机生成用户背景图片
            String bgUrl = super.getRandomBgUrl();
            userExt.setBgUrl(bgUrl);
            //插入用户拓展信息，如果存在则更新
            userExtMapper.insertUserExt(userExt);
            myRedisTemplate.delteKey(extKey);
            tbUserExt.setBgUrl(bgUrl);
        }
        return tbUserExt;
    }

    /**
     * 更新用户拓展信息
     * @param tbUserExt
     * @return
     */
    @Override
    public boolean updateUserExt(TbUserExt tbUserExt) {
        Integer uid = tbUserExt.getUid();
        TbUserExtExample extExample= new TbUserExtExample();
        TbUserExtExample.Criteria criteria = extExample.createCriteria();
        criteria.andUidEqualTo(uid);
        List<TbUserExt> lst = tbUserExtMapper.selectByExample(extExample);
        try {
            if(lst != null && lst.size() > 0) {
                tbUserExtMapper.updateByExampleSelective(tbUserExt,extExample);
            }
            else{
                tbUserExtMapper.insertSelective(tbUserExt);
            }
            String extKey = UserConstants.getUserExtRedisKey(uid);
            TbUserExt userExt = userExtMapper.queryUserExtByUid(uid);
            myRedisTemplate.set(extKey,userExt,7);
            myRedisTemplate.set(UserConstants.getUserDetailRedisKey(uid),userInfoMapper.findUserInfoDetail(uid),7);
            return true;
        } catch (Exception e) {
            logger.error("更新用户拓展信息失败，用户uid为【{}】;异常信息为【{}】",uid,e);
            return false;
        }
    }
    /**
     * 获取用户拓展信息
     * @param uid
     * @return
     */
    public TbUserExt getExt(Integer uid){
        TbUserExt userExt = userExtMapper.queryUserExtByUid(uid);
        String extKey = UserConstants.getUserExtRedisKey(uid);
        if(userExt != null){
            myRedisTemplate.set(extKey,userExt,7);
            return userExt;
        } else {
            TbUserExt ext = new TbUserExt();
            ext.setUid(uid);
            ext.setBgUrl(super.getRandomBgUrl());
            userExtMapper.insertUserExt(ext);
            userExt = userExtMapper.queryUserExtByUid(uid);
            if (userExt == null) {
                userExt = new TbUserExt();
                userExt.setBaseState(Constants.BYTE_ZERO);
                userExt.setIsBidsVerify(Constants.BYTE_ZERO);
                userExt.setIsBuyoutVerify(0);
                return userExt;
            } else {
                myRedisTemplate.set(extKey,userExt,7);
                return userExt;
            }
        }
    }

    public Map<Integer,TbUserExt> getExt(List<Integer> ids){
        logger.info("开始批量查询用户拓展信息！size:{}.uid:{}",ids.size(),ids);
        Map<Integer,TbUserExt> map = new HashMap<Integer,TbUserExt>();
        List<Integer> dbIds = new ArrayList<>();
        for (Integer uid : ids){
            TbUserExt tbUserExt = (TbUserExt)myRedisTemplate.hget(UserConstants.UID_MAP_EXT, uid.toString()); // 缓存用户拓展信息
            if(tbUserExt != null)
                map.put(uid,tbUserExt);
            else
                dbIds.add(uid);
        }
        logger.info("未在缓存中的uid:{}", dbIds.toString());
        if(dbIds.size() > 0){
            TbUserExtExample tbUserExtExample = new TbUserExtExample();
            TbUserExtExample.Criteria criteria = tbUserExtExample.createCriteria();
            criteria.andUidIn(dbIds);
            List<TbUserExt> lstDbExt = tbUserExtMapper.selectByExample(tbUserExtExample);
            logger.info("查询DB拓展信息数量", lstDbExt.size());
            for (TbUserExt ext : lstDbExt){
                myRedisTemplate.hset(UserConstants.UID_MAP_EXT,ext.getUid().toString(),ext); // 缓存用户拓展信息
                map.put(ext.getUid(),ext);
            }
        }
        logger.info("结束批量查询用户拓展信息结果 size:{}",map.size());
        return map;
    }

    /**
     * 获取用户基本信息
     * @param uid
     * @return
     */
    public TbUser getUser(Integer uid){
        TbUser user = this.userMapper.selectByPrimaryKey(uid);
        return user;
    }

}
